package org.eduapp.trains.dao.log.impl;

import org.eduapp.trains.DAOException;
import org.eduapp.trains.dao.BaseDAOImpl;
import org.eduapp.trains.dao.log.LogDAO;
import org.eduapp.trains.model.logs.ModelLogs;
import org.eduapp.trains.utils.UtilsDateTime;
import org.eduapp.trains.utils.UtilsString;
import org.eduapp.trains.web.support.PaginationSupport;
import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 * 
 * @author jeccy
 *
 */
public class LogDAOImpl extends BaseDAOImpl<ModelLogs> implements LogDAO {

	@Override
	public PaginationSupport<ModelLogs> get(ModelLogs model, int pageSize,
			int startIndex, String order, Boolean isDesc) throws DAOException {
		
		DetachedCriteria criteria = DetachedCriteria.forClass(ModelLogs.class);
		
		if (model != null) {
			
			if (model.getLogType() != null) {
				criteria.add(Restrictions.eq("logType", model.getLogType()));
			}
			
			if (model.getLogOperator() != null && 
					UtilsString.isNotEmpty(model.getLogOperator().getId())) {
				criteria.createCriteria("logOperator").add(
						Restrictions.eq("id", model.getLogOperator().getId()));
			}
			
			if (UtilsString.isNotEmpty(model.getLogText())) {
				criteria.add(Restrictions.ilike("logText", model.getLogText(), MatchMode.ANYWHERE));
			}
			
			if (model.getLogCreateTime() != null) {
				criteria.add(Restrictions.sqlRestriction(
					"log_ctime>=?", UtilsDateTime.dateString(model.getLogCreateTime()) , Hibernate.STRING));
			}
			
		}
		
		if (UtilsString.isNotEmpty(order)) {
			if (isDesc != null && isDesc) {
				criteria.addOrder(Order.desc(order));
			} else {
				criteria.addOrder(Order.asc(order));
			}
		} else {
			criteria.addOrder(Order.desc("logCreateTime"));
		}
		
		return findPageByCriteria(criteria, pageSize, startIndex);
	}

}
